package com.sky.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.SysUser;
import com.sky.handler.MyGrantedAuthority;
import com.sky.handler.MyUserDetails;
import com.sky.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @projectName: netty-cloud
 * @package: com.sky.config
 * @className: JdbcUserDatilsService
 * @author: zhl
 * @description: TODO
 * @date: 2024/4/24 14:28
 * @version: 1.0
 */
public class JdbcUserDetailsManager implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username));
        if (sysUser == null) {
            throw new UsernameNotFoundException(username);
        }

        String password = sysUser.getPassword();
        // 对密码进行加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // {bcrypt} ：定义 DelegatingPasswordEncoder.matches() 方法匹配登录密码的加密算法
        // UsernamePasswordAuthenticationFilter.attemptAuthentication()方法中获取登录页面输入的用户名、密码
        String encode = "{bcrypt}" + encoder.encode(password);
        sysUser.setPassword(encode);

        /** 两种方式的选择取决于 WebSecurityConfig.SecurityFilterChain 中配置资源的方式（权限标识集）  **/
        // 添加用户的权限标识集
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new MyGrantedAuthority("USER"));

        UserDetails details = new User(
                sysUser.getUserName(),
                sysUser.getPassword(),
                // 用户账号是否启用
                true,
                // 用户账号是否过期
                true,
                // 用户凭证是否未过期
                true,
                // 用户账户是否未被锁定
                true,
                // 用户权限列表
                authorities
        );

        /** 两种方式的选择取决于 WebSecurityConfig.SecurityFilterChain 中配置资源的方式（角色）  **/
        UserDetails details2 = User.withUsername(sysUser.getUserName())
                .password(sysUser.getPassword())
                // 用户是否禁用
                .disabled(false)
                // 用户账号是否过期
                .credentialsExpired(false)
                // 用户账户是否被锁定
                .accountLocked(false)
                // roles 与 authorities会互相覆盖，后面的会覆盖前面的（配置在后面优先级更高），只能选择其一
                .roles("ADMIN")
                .authorities("FILE","UPLOAD")
                .build();

        // 自定义 UserDetails 类
        MyUserDetails details3 = new MyUserDetails(sysUser,authorities);

        return details3;
    }
}
